<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-4-3
 */

namespace app\admin\controller;

use think\Config;
use think\Db;
use think\Page;
use think\Cache;

class UsersMoney extends Base
{
    /**
     * 构造方法
     */
    public function __construct(){
        parent::__construct();

        $this->users_money_db  = Db::name('users_money');   // 会员充值表
        $this->users_level_db  = Db::name('users_level');   // 会员等级表
        $this->users_db        = Db::name('users');         // 会员信息表
        $this->add_type = [1,4,2]; //添加类型
        $this->reduce_type = [0,3,5]; //减少类型
        $this->assign('add_type', $this->add_type);
        $this->assign('reduce_type', $this->reduce_type);

    }

    // 充值记录列表
    public function money_index()
    {
        $list = array();

        // 查询条件
        $condition = [
            'a.cause_type' => 1,
        ];

        // 应用搜索条件
        $keywords = input('keywords/s');
        if (!empty($keywords)) $condition['a.order_number|b.username|b.nickname'] = array('LIKE', "%{$keywords}%");

        // 支付方式查询
        $pay_method = input('pay_method/s');
        if (!empty($pay_method)) $condition['a.pay_method'] = $pay_method;

        // 会员级别查询
        $level = input('level/s');
        if (!empty($level)) $condition['b.level'] = $level;

        // 订单状态搜索
        $order_status = input('param.status/d');
        if ($order_status) $condition['a.status'] = in_array($order_status, [2, 3]) ? ['IN', [2, 3]] : $order_status;

        // 下单时间查询
        $add_time = input('param.add_time/s');
        if (!empty($add_time)) {
            $add_time = explode('~', $add_time);
            $start = strtotime(rtrim($add_time[0]));
            $finish = strtotime(rtrim($add_time[1]).' 23:59:59');
            $condition['a.add_time'] = ['between', "$start, $finish"];
        }

        // 时间检索条件
        // $begin = strtotime(input('param.add_time_begin/s'));
        // $end = input('param.add_time_end/s');
        // !empty($end) && $end .= ' 23:59:59';
        // $end = strtotime($end);
        // // 时间检索
        // if ($begin > 0 && $end > 0) {
        //     $condition['a.add_time'] = array('between', "$begin, $end");
        // } else if ($begin > 0) {
        //     $condition['a.add_time'] = array('egt', $begin);
        // } else if ($end > 0) {
        //     $condition['a.add_time'] = array('elt', $end);
        // }

        // 分页查询
        $count = $this->users_money_db->alias('a')->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')->where($condition)->count();
        $Page = new Page($count, config('paginate.list_rows'));

        // 数据查询
        $list = $this->users_money_db->field('a.*, b.head_pic, b.username, b.nickname, b.level')
            ->alias('a')
            ->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')
            ->where($condition)
            ->order('a.moneyid desc')
            ->limit($Page->firstRow.','.$Page->listRows)
            ->select();
        foreach ($list as $key => $value) {
            $value['username'] = !empty($value['nickname']) ? $value['nickname'] : $value['username'];
            $value['head_pic'] = get_head_pic($value['head_pic']);
            $value['data'] = unserialize($value['data']);
            $list[$key] = $value;
        }
        $show = $Page->show();
        $this->assign('page', $show);
        $this->assign('list', $list);
        $this->assign('pager', $Page);

        // 会员等级列表
        $usersLevel = $this->users_level_db->field('level_id, level_name')->order('level_value asc')->getAllWithIndex('level_id');
        $this->assign('usersLevel', $usersLevel);

        // 充值状态
        $pay_status_arr = config('global.pay_status_arr');
        $this->assign('pay_status_arr', $pay_status_arr);

        // 是否开启文章付费
        $channelRow = Db::name('channeltype')->where('nid', 'in',['article','download'])->getAllWithIndex('nid');
        foreach ($channelRow as &$val){
            if (!empty($val['data'])) $val['data'] = json_decode($val['data'], true);
        }
        $this->assign('channelRow', $channelRow);

        return $this->fetch();
    }

    // 充值记录编辑
    public function money_edit()
    {
        $param = input('param.');
        $MoneyData = $this->users_money_db->find($param['moneyid']);
        $this->assign('MoneyData',$MoneyData);
        $UsersData = $this->users_db->find($MoneyData['users_id']);
        $this->assign('UsersData',$UsersData);

        // 支付宝查询订单
        if ('alipay' == $MoneyData['pay_method']) {
            $return = $this->check_alipay_order($MoneyData['order_number']);
            $this->assign('return',$return);
        }

        // 微信查询订单
        if ('wechat' == $MoneyData['pay_method']) {
            $return = $this->check_wechat_order($MoneyData['order_number']);
            $this->assign('return',$return);
        }

        // 人为处理订单
        if ('artificial' == $MoneyData['pay_method']) {
            $return = '人为处理';
            $this->assign('return',$return);
        }

        // 获取订单状态
        $pay_status_arr = Config::get('global.pay_status_arr');
        $this->assign('pay_status_arr',$pay_status_arr);

        // 支付方式
        $pay_method_arr = config('global.pay_method_arr');
        $this->assign('pay_method_arr',$pay_method_arr);

        return $this->fetch();
    }

    /**
     * 删除充值记录
     */
    public function money_del()
    {
        if (IS_POST) {
            $id_arr = input('del_id/a');
            $id_arr = eyIntval($id_arr);
            if(!empty($id_arr)){
                $result = Db::name('users_money')->field('order_number')
                    ->where([
                        'moneyid'    => ['IN', $id_arr],
                    ])->select();
                $order_number_list = get_arr_column($result, 'order_number');

                $r = Db::name('users_money')->where([
                    'moneyid'    => ['IN', $id_arr],
                ])
                    ->cache(true, null, "users_money")
                    ->delete();
                if($r !== false){
                    adminLog('删除充值记录：'.implode(',', $order_number_list));
                    $this->success('删除成功');
                }
            }
            $this->error('删除失败');
        }
        $this->error('非法访问');
    }

    // 标记订单逻辑
    public function money_mark_order()
    {
        if (IS_POST) {
            $moneyid     = input('param.moneyid/d');

            // 查询订单信息
            $MoneyData = $this->users_money_db->where([
                'moneyid'     => $moneyid,
            ])->find();

            // 处理订单逻辑
            if (in_array($MoneyData['status'], [1,3])) {

                $users_id = $MoneyData['users_id'];
                $order_number = $MoneyData['order_number'];
                $return = '';
                if ('alipay' == $MoneyData['pay_method']) { // 支付宝查询订单
                    $return = $this->check_alipay_order($order_number);
                } else if ('wechat' == $MoneyData['pay_method']) { // 微信查询订单
                    $return = $this->check_wechat_order($order_number);
                } else if ('artificial' == $MoneyData['pay_method']) { // 手工充值订单
                    $return = '手工充值';
                }

                $result = [
                    'users_id'    => $users_id,
                    'order_number'=> $order_number,
                    'status'      => '手动标记为已充值订单',
                    'details'     => '充值详情：'.$return,
                    'pay_method'  => 'artificial', //人为处理
                    'money'       => $MoneyData['money'],
                    'users_money' => $MoneyData['users_money'],
                ];

                // 标记为未付款
                if (3 == $MoneyData['status']) {
                    $result['status'] = '手动标记为未付款订单';
                } else if (1 == $MoneyData['status']) {
                    $result['status'] = '手动标记为已充值订单';
                }

                // 修改会员充值明细表对应的订单数据，存入返回的数据，订单标记为已付款
                $Where = [
                    'moneyid'  => $MoneyData['moneyid'],
                    'users_id'  => $users_id,
                ];

                $UpdateData = [
                    'pay_details'   => serialize($result),
                    'update_time'   => getTime(),
                ];

                // 标记为未付款时则状态更新为1
                if (3 == $MoneyData['status']) {
                    $UpdateData['status'] = 1;
                } else if (1 == $MoneyData['status']) {
                    $UpdateData['status'] = 3;
                    $UpdateData['pay_method'] = 'admin_pay';
                    $UpdateData['wechat_pay_type'] = '';
                }

                $IsMoney = $this->users_money_db->where($Where)->update($UpdateData);

                if (!empty($IsMoney)) {
                    // 同步修改会员的金额
                    $UsersData = [
                        'update_time' => getTime(),
                    ];

                    // 标记为未付款时则减去金额
                    if (3 == $MoneyData['status']) {
                        $UsersData = $this->users_db->field('users_money')->find($users_id);
                        if ($UsersData['users_money'] <= $MoneyData['money']) {
                            $UsersData['users_money'] = 0;
                        }else{
                            $UsersData['users_money'] = Db::raw('users_money-'.$MoneyData['money']);
                        }
                    } else if (1 == $MoneyData['status']) {
                        $UsersData['users_money'] = Db::raw('users_money+'.$MoneyData['money']);
                    }

                    $IsUsers = $this->users_db->where('users_id',$users_id)->update($UsersData);
                    if (!empty($IsUsers)) {
                        $this->success('操作成功');
                    }
                }
            }
            $this->error('操作失败');
        }
    }


    // 充值明细列表
    public function eyou_money_recharge_index()
    {
        $list = array();

        // 查询条件
        $condition = [
            'a.status' => 3
        ];

        // 应用搜索条件
        $keywords = input('keywords/s');
        if (!empty($keywords)) $condition['a.order_number|b.username'] = array('LIKE', "%{$keywords}%");

        // 支付方式查询
        $cause_type = input('cause_type/d');
        if (is_numeric($cause_type) && -1 < $cause_type) $condition['a.cause_type'] = $cause_type;

        //支付规则
        $type = input('type/d', 0);
        if (!empty($type) && $cause_type < 0){
            if (1 == $type){
                $condition['a.cause_type'] = ['in',$this->add_type];
            }else{
                $condition['a.cause_type'] = ['in',$this->reduce_type];
            }
        }

        // 会员级别查询
        $level = input('level/s');
        if (!empty($level)) $condition['b.level'] = $level;

        // 操作时间查询
        $add_time = input('param.add_time/s');
        if (!empty($add_time)) {
            $add_time = explode('~', $add_time);
            $start = strtotime(rtrim($add_time[0]));
            $finish = strtotime(rtrim($add_time[1]).' 23:59:59');
            $condition['a.add_time'] = ['between', "$start, $finish"];
        }

        // 分页查询
        $count = $this->users_money_db->alias('a')->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')->where($condition)->count();
        $Page = new Page($count, config('paginate.list_rows'));

        // 数据查询
        $list = $this->users_money_db->field('a.*, b.head_pic, b.username, b.nickname, b.level,b.is_mobile,b.thirdparty')
            ->alias('a')
            ->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')
            ->where($condition)
            ->order('a.moneyid desc')
            ->limit($Page->firstRow.','.$Page->listRows)
            ->select();
        $users_ids = get_arr_column($list,'users_id');
        $total_add_money = $total_reduce_money = 0;
        foreach ($list as $key => $value) {
            if (in_array($value['cause_type'],$this->add_type)){
                $total_add_money += $value['money'];
            }else{
                $total_reduce_money += $value['money'];
            }
            $value['username'] = !empty($value['nickname']) ? $value['nickname'] : $value['username'];
            $value['head_pic'] = get_head_pic($value['head_pic']);
            $list[$key] = $value;
        }
        $show = $Page->show();
        $this->assign('page', $show);
        $this->assign('list', $list);
        $this->assign('pager', $Page);
        $this->assign('total_add_money', $total_add_money);
        $this->assign('total_reduce_money', $total_reduce_money);
        $this->assign('list_row', count($list));

        // 会员等级列表
        $usersLevel = $this->users_level_db->field('level_id, level_name')->order('level_value asc')->getAllWithIndex('level_id');
        $this->assign('usersLevel', $usersLevel);

        // 充值状态
        $pay_status_arr = config('global.pay_status_arr');
        $this->assign('pay_status_arr', $pay_status_arr);

        // 充值类型
        $pay_cause_type_arr = config('global.pay_cause_type_arr');
        $this->assign('pay_cause_type_arr', $pay_cause_type_arr);

        /*微信登录插件*/
        $wxlogin = [];
        if (is_dir('./weapp/WxLogin/')) {
            $wxlogin = Db::name('weapp_wxlogin')->where(['users_id'=>['IN', $users_ids]])->getAllWithIndex('users_id');
        }
        $this->assign('wxlogin',$wxlogin);
        /*end*/

        /*QQ登录插件*/
        $qqlogin = [];
        if (is_dir('./weapp/QqLogin/')) {
            $qqlogin = Db::name('weapp_qqlogin')->where(['users_id'=>['IN', $users_ids]])->getAllWithIndex('users_id');
        }
        $this->assign('qqlogin',$qqlogin);
        /*end*/

        /*微博登录插件*/
        $wblogin = [];
        if (is_dir('./weapp/Wblogin/')) {
            $wblogin = Db::name('weapp_wblogin')->where(['users_id'=>['IN', $users_ids]])->getAllWithIndex('users_id');
        }
        $this->assign('wblogin',$wblogin);
        /*end*/


        return $this->fetch();
    }

    /**
     * 积分设置
     */
    public function conf()
    {
        if (IS_POST) {
            $post     = input('post.');
            $functionLogic = new \app\common\logic\FunctionLogic;
            $functionLogic->scoreConf($post);
            $this->success("操作成功", url('UsersScore/conf'));
        }
        $score = getUsersConfigData('score');
        $this->assign('score', $score);

        return $this->fetch();
    }
}